package gcontent.entities.content.html;

import java.util.ArrayList;
import gcontent.entities.Content; 
import gcontent.entities.Site;
import gcontent.entities.content.error.ContentEx;
import gcontent.record.error.RecordEx;

import org.apache.log4j.Logger;
import org.htmlparser.Parser;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.ParserException;

public class ContentHTML extends Content {
	
	public static final String MIMETYPE_HTML = "text/html";
	
	private static Logger log = Logger.getLogger(ContentHTML.class);	
	private TagFilter tag_f = null;
	private String title;
	
	public ContentHTML()
	{	
		super();
	}
		
	public String getFormat()
	{
		return MIMETYPE_HTML;
	}
	
	public void setTitle(String title)
	{
		this.title = title;
	}
	
	public String getTitle()
	{
		return this.title;
	}

	public void parse()
	{			
		/* content parsed? */ 
		if(this.tag_f != null)
			return;
		
		try {
			TagFilter tag_f;
			Parser parser;

			
			parser = new Parser();
			tag_f = new TagFilter(this);

			parser.setFeedback(Parser.DEVNULL);
			parser.setInputHTML(new String(this.body));		
		
			/* do parse */
			parser.parse(tag_f);
		
			/* content was parsed */
			this.tag_f = tag_f;

		} catch(ParserException ex) {
			ex.printStackTrace();
		}
	}
	
	private void save_references() throws RecordEx, ContentEx
	{		
		if(this.tag_f == null)
			return;

		for(int i = 0; i < this.ref_list.size(); i++) {
			RefHTML ref_val;
				
			ref_val = (RefHTML)this.ref_list.get(i);
			ref_val.save();				
		}
		
	}
	
	public void save() throws RecordEx, ContentEx
	{	
		/* fill info of content */
		parse();
		
		/* create entry */
		this.id = (Integer)this.record.execProc("PROC_CreateContentHTML", 
				  null,
				  null,
				  this.title,
				  this.body,
				  this.body == null? 0 : this.body.length,
				  this.last_modified,
				  this.truncated
				  );	
		
		/* save references */
		save_references();									  								
	}
}